package com.vader.boot.RedPackage;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author Vader
 * @date 2022/4/25
 **/
@RestController
@Slf4j
@RequestMapping("/red")
public class RedPackageController {

    public static final String RED_PACKAGE_HOME = "red_package_home:";
    public static final String RED_PACKAGE_USER = "red_package_user:";

    @Resource
    private RedisTemplate redisTemplate;


    @PostMapping("/send")
    public String sendRedPackage(@RequestParam Integer totalMoney, @RequestParam int memberCount) {
        int useMoney = 0;
        Random random = new Random();
        Integer[] redNumbers = new Integer[memberCount];
        for (int i = 0; i < redNumbers.length; i++) {
            if (i == memberCount - 1) {
                redNumbers[i] = totalMoney - useMoney;
            } else {
                int avg = ((totalMoney - useMoney) / (memberCount - i)) * 2;
                redNumbers[i] = random.nextInt(avg - 1) + 1;
            }
            useMoney += redNumbers[i];
        }
        String key = RED_PACKAGE_HOME + "vader";
        redisTemplate.opsForList().leftPushAll(key, redNumbers);
        redisTemplate.expire(key, 1, TimeUnit.DAYS);
        return JSONObject.toJSONString(redNumbers);
    }


    @PostMapping("rob")
    public String robRedPackage(@RequestParam Integer userId, @RequestParam String key) {
        String userKey = RED_PACKAGE_USER + key;
        Object user = redisTemplate.opsForHash().get(userKey, userId);
        if (Objects.nonNull(user)) {
            return "不可重复抢红包";
        }
        Object money = redisTemplate.opsForList().leftPop(key);
        if (Objects.isNull(money)) {
            return "已经抢光了";
        }
        redisTemplate.opsForHash().put(userKey, userId, money);
        return String.valueOf(money);
    }


}
